/**
 * 评估清单表格组件
 */

import React, { useState, useMemo } from 'react';
import { 
  Plus, 
  Trash2, 
  Edit3, 
  Search, 
  ArrowUpDown,
  ArrowUp,
  ArrowDown,
  Check
} from 'lucide-react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { showMessage } from '@/components/common/MessageTip';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';
import type { EvaluationItem, EvaluationMetadata } from '@/types/ProofMapper';
import MetadataPanel from './MetadataPanel';
import EditItemDialog from './EditItemDialog';
import PaginationControls from './PaginationControls';
import './styles.css';

interface EvaluationTableProps {
  className?: string;
  metadata?: EvaluationMetadata;
}

// 评估模块颜色映射
const moduleColorMap: Record<string, string> = {
  '应用安全': 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
  '数据安全': 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
  '平台安全': 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
  '基础设施安全': 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200',
  '合作安全': 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200'
};


const EvaluationTable: React.FC<EvaluationTableProps> = ({ 
  className = '', 
  metadata = {
    source_file: '未知文件',
    generated_at: new Date().toISOString(),
    version: 'v1.0.0'
  }
}) => {
  const {
    evaluationItems,
    selectedItems,
    sortConfig,
    filterConfig,
    sortedItems,
    selectedItemsCount,
    hasSelectedItems,
    updateEvaluationItem,
    deleteEvaluationItem,
    addEvaluationItem,
    toggleItemSelection,
    setSortConfig,
    setFilterConfig
  } = useProofMapper();

  const [editingItem, setEditingItem] = useState<Partial<EvaluationItem> | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedModule, setSelectedModule] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [showAddForm, setShowAddForm] = useState(false);
  
  // 删除确认相关状态
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<{id: string, name: string} | null>(null);

  // 当从第三步返回第二步时，筛选栏UI为空，但上下文filterConfig可能还保留旧值
  // 这里在组件挂载时（以及当本地筛选UI均为空时）清空全局筛选条件并重置分页
  React.useEffect(() => {
    if (!searchTerm && !selectedModule && !selectedCategory) {
      setFilterConfig({});
      setCurrentPage(1);
    }
    // 仅在初始或本地筛选为空时重置，避免干扰用户正进行的筛选
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchTerm, selectedModule, selectedCategory]);
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const pageSizeOptions = [5, 10, 20, 50];

  // 获取所有模块和类别（allCategories为全量类别，filteredCategories随模块筛选变化）
  const { modules, allCategories, filteredCategories } = useMemo(() => {
    const moduleSet = new Set(evaluationItems.map(item => item.module));
    const allCategorySet = new Set(evaluationItems.map(item => item.category));
    const modulesArr = Array.from(moduleSet).sort();
    const allCategoriesArr = Array.from(allCategorySet).sort();

    // 根据已选模块动态计算可选类别
    const categoriesByModule = selectedModule
      ? Array.from(new Set(
          evaluationItems
            .filter(item => item.module === selectedModule)
            .map(item => item.category)
        )).sort()
      : allCategoriesArr;

    return {
      modules: modulesArr,
      allCategories: allCategoriesArr,
      filteredCategories: categoriesByModule
    };
  }, [evaluationItems, selectedModule]);
  
  // 计算分页数据
  const paginatedItems = useMemo(() => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return sortedItems.slice(startIndex, endIndex);
  }, [sortedItems, currentPage, pageSize]);

  // 计算筛选后的全选状态（仅对当前筛选结果sortedItems判断）
  const allFilteredSelected = useMemo(() => {
    if (sortedItems.length === 0) return false;
    return sortedItems.every(item => selectedItems.includes(item.id));
  }, [sortedItems, selectedItems]);
  
  // 计算总页数
  const totalPages = useMemo(() => {
    return Math.ceil(sortedItems.length / pageSize);
  }, [sortedItems.length, pageSize]);
  
  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };
  
  // 处理每页条数变化
  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理排序
  const handleSort = (field: keyof EvaluationItem) => {
    const newDirection = 
      sortConfig.field === field && sortConfig.direction === 'asc' 
        ? 'desc' 
        : 'asc';
    
    setSortConfig({ field, direction: newDirection });
  };

  // 获取排序图标
  const getSortIcon = (field: keyof EvaluationItem) => {
    if (sortConfig.field !== field) {
      return <ArrowUpDown className="h-4 w-4 text-muted-foreground" />;
    }
    return sortConfig.direction === 'asc' 
      ? <ArrowUp className="h-4 w-4 text-primary" />
      : <ArrowDown className="h-4 w-4 text-primary" />;
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setFilterConfig({
      ...filterConfig,
      search_term: value || undefined
    });
  };

  // 处理模块和类别过滤
  const handleModuleFilter = (module: string) => {
    setSelectedModule(module);

    // 当模块变化时，如果当前选中的类别不在新模块的类别集合中，则清空类别筛选
    // 先计算该模块下的类别列表（与useMemo保持一致的逻辑）
    const newFilteredCategories = module
      ? Array.from(new Set(
          evaluationItems
            .filter(item => item.module === module)
            .map(item => item.category)
        )).sort()
      : allCategories;

    const nextCategory = selectedCategory && newFilteredCategories.includes(selectedCategory)
      ? selectedCategory
      : '';

    if (nextCategory !== selectedCategory) {
      setSelectedCategory('');
    }

    // 切换模块时重置分页到第一页
    setCurrentPage(1);

    setFilterConfig({
      ...filterConfig,
      module: module || undefined,
      category: nextCategory || undefined
    });
  };

  const handleCategoryFilter = (category: string) => {
    setSelectedCategory(category);
    setFilterConfig({
      ...filterConfig,
      category: category || undefined
    });
  };

  // 开始编辑
  const startEdit = (item: EvaluationItem) => {
    setEditingItem(item);
  };


  // 保存编辑
  const handleSaveEdit = (editForm: Partial<EvaluationItem>) => {
    if (editingItem?.id) {
      const updatedItem: EvaluationItem = {
        ...editingItem,
        ...editForm,
        updated_at: new Date().toISOString()
      } as EvaluationItem;
      
      updateEvaluationItem(updatedItem);
      setEditingItem(null);
      showMessage('success', '评估项已更新');
    }
  };

  // 打开删除确认对话框
  const openDeleteConfirm = (id: string) => {
    const item = evaluationItems.find(item => item.id === id);
    if (item) {
      // 使用查验点作为项目名称
      setItemToDelete({
        id: item.id,
        name: item.checkpoint
      });
      setShowDeleteConfirm(true);
    }
  };

  // 关闭删除确认对话框
  const closeDeleteConfirm = () => {
    setShowDeleteConfirm(false);
    setItemToDelete(null);
  };

  // 确认删除项目
  const confirmDelete = () => {
    if (itemToDelete) {
      // 防止重复调用
      const itemExists = evaluationItems.some(item => item.id === itemToDelete.id);
      if (!itemExists) {
        showMessage('warning', '项目已不存在');
        closeDeleteConfirm();
        return;
      }
      
      deleteEvaluationItem(itemToDelete.id);
      showMessage('success', '评估项已删除');
      closeDeleteConfirm();
    }
  };

  // 添加新项目
  const handleAddItem = (newItemForm: Partial<EvaluationItem>) => {
    if (!newItemForm.module || !newItemForm.category || !newItemForm.checkpoint || !newItemForm.materials?.length) {
      showMessage('error', '请填写完整的评估项信息');
      return;
    }

    const newItem: EvaluationItem = {
      id: crypto.randomUUID(),
      module: newItemForm.module,
      category: newItemForm.category,
      checkpoint: newItemForm.checkpoint,
      materials: newItemForm.materials,
      notes: newItemForm.notes || '',
      selected: false,
      updated_at: new Date().toISOString()
    };

    addEvaluationItem(newItem);
    setShowAddForm(false);
    showMessage('success', '评估项已添加');
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    // 只对当前筛选后的项目进行选择/取消选择
    if (allFilteredSelected) {
      // 取消选择当前筛选结果中已选中的条目
      sortedItems.forEach(item => {
        if (selectedItems.includes(item.id)) {
          toggleItemSelection(item.id);
        }
      });
    } else {
      // 选择当前筛选结果中未被选中的条目
      sortedItems.forEach(item => {
        if (!selectedItems.includes(item.id)) {
          toggleItemSelection(item.id);
        }
      });
    }
  };

  // 批量导出选中项
  const handleExportSelected = () => {
    if (!hasSelectedItems) {
      showMessage('warning', '请先选择要导出的项目');
      return;
    }
    showMessage('info', `准备导出 ${selectedItemsCount} 个选中项目`);
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* 元数据面板 */}
      <MetadataPanel metadata={metadata} />

      {/* 表格标题和工具栏 */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="flex items-center justify-center w-10 h-10 bg-green-500/10 rounded-lg">
              <Check className="h-5 w-5 text-green-500" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-foreground">评估清单展示区</h2>
              <p className="text-sm text-muted-foreground">
                AI解析结果，支持编辑、删除和新增操作
              </p>
            </div>
          </div>
          
          {/* 操作按钮 */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowAddForm(true)}
              className="inline-flex items-center gap-2 px-3 py-2 bg-primary text-primary-foreground text-sm rounded-md hover:bg-primary/90 transition-colors"
            >
              <Plus className="h-4 w-4" />
              新增
            </button>
            
            <button
              onClick={handleExportSelected}
              disabled={!hasSelectedItems}
              className="inline-flex items-center gap-2 px-3 py-2 bg-secondary text-secondary-foreground text-sm rounded-md hover:bg-secondary/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              导出选中 ({selectedItemsCount})
            </button>
          </div>
        </div>

        {/* 搜索和过滤 */}
        <div className="flex items-center gap-4 mb-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <input
              type="text"
              placeholder="搜索评估项..."
              value={searchTerm}
              onChange={(e) => handleSearch(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-background border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
          
          <div className="flex items-center gap-2">
            <select
              value={selectedModule}
              onChange={(e) => handleModuleFilter(e.target.value)}
              className="px-3 py-2 bg-background border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-w-[120px]"
            >
              <option value="">所有模块</option>
              {modules.map(module => (
                <option key={module} value={module}>{module}</option>
              ))}
            </select>

            <select
              value={selectedCategory}
              onChange={(e) => handleCategoryFilter(e.target.value)}
              className="px-3 py-2 bg-background border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring min-w-[120px]"
            >
              <option value="">所有类别</option>
              {filteredCategories.map(category => (
                <option key={category} value={category}>{category}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* 表格 */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-muted/50">
              <tr>
                <th className="w-12 px-4 py-3 text-left">
                  <input
                    type="checkbox"
                    checked={allFilteredSelected}
                    onChange={handleSelectAll}
                    className="rounded border-input"
                  />
                </th>
                <th className="px-4 py-3 text-left">
                  <button
                    onClick={() => handleSort('module')}
                    className="flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary transition-colors"
                  >
                    评估模块
                    {getSortIcon('module')}
                  </button>
                </th>
                <th className="px-4 py-3 text-left">
                  <button
                    onClick={() => handleSort('category')}
                    className="flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary transition-colors"
                  >
                    类别
                    {getSortIcon('category')}
                  </button>
                </th>
                <th className="px-4 py-3 text-left">
                  <button
                    onClick={() => handleSort('checkpoint')}
                    className="flex items-center gap-2 text-sm font-medium text-foreground hover:text-primary transition-colors"
                  >
                    查验点
                    {getSortIcon('checkpoint')}
                  </button>
                </th>
                <th className="px-4 py-3 text-left">
                  <span className="text-sm font-medium text-foreground">证明材料</span>
                </th>
                <th className="px-4 py-3 text-left">
                  <span className="text-sm font-medium text-foreground">备注</span>
                </th>
                <th className="w-20 px-4 py-3 text-center">
                  <span className="text-sm font-medium text-foreground">操作</span>
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {paginatedItems.map((item, index) => (
                <tr 
                  key={item.id} 
                  className="hover:bg-muted/25 transition-all duration-200"
                  style={{
                    opacity: 0,
                    animationName: 'fadeIn',
                    animationDuration: '0.5s',
                    animationTimingFunction: 'ease',
                    animationFillMode: 'forwards',
                    animationDelay: `${index * 50}ms`
                  }}>
                  <td className="px-4 py-3">
                    <input
                      type="checkbox"
                      checked={selectedItems.includes(item.id)}
                      onChange={() => toggleItemSelection(item.id)}
                      className="rounded border-input"
                    />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${moduleColorMap[item.category] || 'bg-gray-100 text-gray-800'}`}>
                        {item.module}
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${moduleColorMap[item.category] || 'bg-gray-100 text-gray-800'}`}>
                        {item.category}
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-foreground">{item.checkpoint}</span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex flex-wrap gap-1 max-h-20 overflow-y-auto pr-2 custom-scrollbar">
                      {item.materials.map((material, idx) => (
                        <span
                          key={idx}
                          className="inline-flex items-center px-2 py-1 bg-secondary/50 text-secondary-foreground rounded text-xs hover:bg-secondary/70 transition-colors"
                        >
                          {material}
                        </span>
                      ))}
                      {item.materials.length > 3 && (
                        <span className="text-xs text-muted-foreground">
                          共 {item.materials.length} 项
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-muted-foreground">{item.notes}</span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => startEdit(item)}
                        className="p-1 text-primary hover:bg-primary/10 rounded transition-colors"
                      >
                        <Edit3 className="h-4 w-4" />
                      </button>
                      <button
                        onClick={() => openDeleteConfirm(item.id)}
                        className="p-1 text-destructive hover:bg-destructive/10 rounded transition-colors"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 空状态 */}
        {sortedItems.length === 0 && (
          <div className="text-center py-12">
            <div className="text-muted-foreground mb-2">暂无评估项</div>
            <p className="text-sm text-muted-foreground">
              {evaluationItems.length === 0 
                ? '请先上传文件进行AI解析' 
                : '当前筛选条件下没有匹配的项目'
              }
            </p>
          </div>
        )}
        
        {/* 分页控件 */}
        {sortedItems.length > 0 && (
          <div className="border-t border-border p-4">
            <PaginationControls
              currentPage={currentPage}
              totalPages={totalPages}
              pageSize={pageSize}
              pageSizeOptions={pageSizeOptions}
              totalItems={sortedItems.length}
              onPageChange={handlePageChange}
              onPageSizeChange={handlePageSizeChange}
            />
          </div>
        )}
      </div>

      {/* 编辑弹窗 */}
      {(editingItem || showAddForm) && (
        <EditItemDialog
          item={editingItem || {}}
          modules={modules}
          categories={allCategories}
          onSave={editingItem ? handleSaveEdit : handleAddItem}
          onCancel={() => {
            setEditingItem(null);
            setShowAddForm(false);
          }}
        />
      )}

      {/* 删除确认弹窗 */}
      <DeleteConfirmModal
        isOpen={showDeleteConfirm}
        onClose={closeDeleteConfirm}
        onConfirm={confirmDelete}
        title="确认删除评估项"
        itemName={itemToDelete?.name || ''}
        message="您确定要删除以下评估项吗？"
        dangerMessage="此操作不可撤销，删除后数据将无法恢复。"
      />
    </div>
  );
};

export default EvaluationTable;
